<template>
	<view :class="isPc ? 'chat-pc flex-page-wrapper' : 'chat flex-page-wrapper'">
		<!-- <uni-nav-bar statusBar backgroundColor="#1E234B" color="#fff" :title="personDetail.personName">

		</uni-nav-bar> -->
		<view class="flex-page chat1">
			<scroll-view :scroll-top="scrollTop" @scroll="scroll" show-scrollbar scroll-y="true" class="scroll-Y" @scrolltoupper="upper" @scrolltolower="lower">
				<view class="scroll-view-item">
					<view class="item" v-if="statusDetail.unlimited">
						<!-- <view class="time">在对方回复你之前，可发送 {{ 3 }} 条信息</view> -->
						<view class="time">点击头像查看名片</view>
					</view>
					<view class="item" v-else>
						<view class="time" v-if="!statusDetail.receive">在对方回复你之前，可发送 {{ statusDetail.maxNum }} 条信息</view>
					</view>
					<view class="item" v-for="(item, index) in list" :key="index">
						<view class="time" v-if="showTime(item.createdTime, index)">{{ time(item.createdTime) }}</view>
						<view class="item1" :class="item.memberUuid == userInfo.uuid ? 'item-right' : 'item-left'">
							<view class="avatar" @click="avatarFn(item)" :style="{ backgroundImage: `url(${ item.avatarUrl + '?x-image-process=image/resize,w_100,limit_0' })` }" v-if="[1, 2].includes(item.contentType)">
							</view>
							<!-- contentType (integer, optional): 1：文本 2：线下邀约 3：非官方地址提示 4 关闭在线交流提示 5 会话申请 , -->
							<view class="content" v-if="[1, 2].includes(item.contentType)" :class="item.contentType == 1 ? 'text-content' : ''">
								<view class="texts" v-if="item.contentType == 1">{{ item.content }}</view>
								<view class="card" v-if="item.contentType == 2">
									<div class="card-title">
										<div class="left">线下会面</div>
										<div class="right" v-if="huimianData(item.extendContent).acceptStatus == 1">已接受</div>
										<div class="right" style="color: red;" v-if="huimianData(item.extendContent).acceptStatus == 2">已拒绝</div>
									</div>
									<div class="card-content">
										<div class="card-content1">{{ huimianData(item.extendContent).theme }}</div>
										<div class="card-content2">
											<image class="icon" src="https://static.inclusionconf.com/static/images/chat/time-icon.png" mode="widthFix"></image>
											<div class="text">{{ huimianData(item.extendContent).meetingDateValue }} {{ huimianData(item.extendContent).startTime }}-{{ huimianData(item.extendContent).endTime }}</div>
										</div>
										<div class="card-content2" v-if="huimianData(item.extendContent).meetingAddressDesc">
											<image class="icon" src="https://static.inclusionconf.com/static/images/chat/addr-icon.png" mode="widthFix"></image>
											<div class="text">{{ huimianData(item.extendContent).meetingAddressDesc }}</div>
										</div>
										<div class="card-content2" v-else>
											<image class="icon" src="https://static.inclusionconf.com/static/images/chat/addr-icon.png" mode="widthFix"></image>
											<div class="text">{{ huimianData(item.extendContent).meetingAddressValue }}</div>
										</div>
										<div class="card-content3" v-if="huimianData(item.extendContent).meetingAddress == 'other'">（非官方会面地点）</div>
										<div class="card-content4" v-if="huimianData(item.extendContent).acceptStatus == 0 && item.memberUuid != userInfo.uuid">
											<div class="btn" @click="rejectHuimian(huimianData(item.extendContent).uuid, () => setItem(item, 2))">拒绝</div>
											<div class="btn on" @click="acceptHuimian(huimianData(item.extendContent).uuid, () => setItem(item, 1))">接受</div>
										</div>
									</div>
								</view>
							</view>
							<view class="tips" v-else>
								<view class="tips-item1" v-if="item.contentType == 3">{{ item.content }}</view>
								<view class="tips-item2" v-if="item.contentType == 4" v-html="item.content"></view>
								<view class="tips-item3" v-if="item.contentType == 5">{{ item.content }}</view>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>
		<!-- <view class="chat2" :style="{ transform: `translateY(${ inputTop })` }" v-if="statusDetail.receive && (!statusDetail.unlimited && statusDetail.surplusNum <= 0)">
			<textarea v-if="isPc" v-model="val" confirm-type="send" @keyup.native.enter="sendMsg" class="chat2-2" name="" id="" placeholder="发消息…"></textarea>
			<input v-else class="chat2-2" :adjust-position="false" type="text" v-model="val" confirm-type="send" placeholder="发消息…" @keyboardheightchange="keyboardheightchange" @confirm="sendMsg" />
		</view> -->
		<view class="chat2" :style="{ transform: `translateY(${ inputTop })` }" v-if="!(!statusDetail.unlimited && statusDetail.surplusNum <= 0)">
			<!-- <input class="chat2-2" :adjust-position="true" type="text" v-model="val" confirm-type="send" placeholder="发消息…" @keyboardheightchange="keyboardheightchange" @confirm="sendMsg" /> -->
			<uni-easyinput :adjust-position="false" type="text" v-model="val" confirm-type="send" placeholder="发消息…" @keyboardheightchange="keyboardheightchange" @confirm="sendMsg" :inputBorder="false" :clearable="false" placeholderStyle="fontSize: 15px">
				<template #right>
					<div class="send-icon" @click="sendMsg">
						<image class="icon" src="https://static.inclusionconf.com/static/images/chat/send-icon.png" mode="widthFix"></image>
					</div>
				</template>
			</uni-easyinput>
			<!-- <view class="chat2-4" @click="sendMsg" v-if="showSend">
				发送
			</view> -->
			<image class="chat2-3" v-if="statusDetail.receive" @click="huimian" src="https://static.inclusionconf.com/static/images/chat/foot-icon4-active.png" mode="heightFix"></image>
		</view>
		<xianxia-huimian v-if="showCardMask" @close="showCardMask = false" @success="successFn" :personUuid="personUuid"></xianxia-huimian>
	</view>
</template>

<script>
	// #ifdef MP-WEIXIN
	import WebSocketClient from '@/uni_modules/StompjsRabbitMQClass-StompjsRabbitMQClass/js_sdk/StompJSRabbitMQClass.js'
	// #endif
	import {
		wsUrl
	} from '@/api/base.js'
	import protal from '@/api/protal.js'

	export default {
		data() {
			return {
				focus: false,
				showSend: false,
				showCardMask: false,
				list: [],
				personUuid: '',
				uuid: '',
				type: '',
				detail: {},
				roomId: '',
				pageNum: 0,
				val: '',
				scrollTop: 0,
				oldTop: 0,
				total: 0,
				leftPageNum: 0,
				waterfallList: [],
				stompWebsocket: null,
				isListConnect: false,
				connectList: [],
				inputTop: 0,
				timer: null,
				userInfo: {},
				statusDetail: {},
				lastTime: '',
				personDetail: {}
			}
		},
		async onLoad(option) {
			await this.getPersonDetail(this)
			this.personUuid = option.personUuid
			this.uuid = option.uuid
			this.type = option.type
			this.init()
			this.initWS()
			this.businesscarddetailById()
		},
		beforeDestroy() {
			// #ifdef MP-ALIPAY
			clearInterval(this.timer)
			// #endif
			// #ifdef MP-WEIXIN
			this.stompWebsocket.disconnect()
			// #endif
		},
		onHide() {
			// #ifdef MP-ALIPAY
			clearInterval(this.timer)
			// #endif
			// #ifdef MP-WEIXIN
			this.stompWebsocket.disconnect()
			// #endif
		},
		computed: {
			cardItem() {
				return v => {
					if (v && v.extendContent) {
						return JSON.parse(v.extendContent)
					} else {
						return {}
					}
				}
			},
			time() {
				return v => {
					const date = new Date(v)
					if (!date.getFullYear()) {
						return ''
					}
					const currentDate = new Date()
					const dateDay = Math.floor(date.getTime() / (1000 * 60 * 60 * 24))
					const currentDay = Math.floor(currentDate.getTime() / (1000 * 60 * 60 * 24))
					if (dateDay == currentDay) { // 当天就只显示HH:mm
						return this.dubble(date.getHours()) + ':' + this.dubble(date.getMinutes())
					} else if ((dateDay + 1) == currentDay) {
						return '昨天 ' + this.dubble(date.getHours()) + ':' + this.dubble(date.getMinutes())
					} else if ((dateDay + 2) == currentDay) {
						return '前天 ' + this.dubble(date.getHours()) + ':' + this.dubble(date.getMinutes())
					} else {
						return this.dubble(date.getFullYear()) + '-' + (this.dubble(date.getMonth()) + 1) + '-' + this
							.dubble(date.getDate()) + ' ' + this.dubble(date.getHours()) + ':' + this.dubble(date
								.getMinutes())
					}
				}
			},
			showTime() {
				return (time, index) => {
					if (index == 0) {
						return true
					} else {
						if (new Date(time).getTime() > (new Date(this.list[index - 1].createdTime).getTime() + 5 * 60 *
								1000)) { // 超过5分钟就显示时间
							return true
						}
						return false
					}
				}
			}
		},
		methods: {
			businesscarddetailById() {
				protal.businesscarddetailById(this.personUuid).then(res => {
					this.personDetail = res.data
					
					uni.setNavigationBarTitle({
						title: res.data.personName
					})
				})
			},
			setItem(item, status) {
				const obj = this.huimianData(item.extendContent)
				obj.acceptStatus = status
				item.extendContent = JSON.stringify(obj)
				const index = this.list.findIndex(x => x.uuid == item.uuid)
				this.list.splice(index, 1, item)
			},
			huimianData(data) {
				if (data) {
					return JSON.parse(data)
				}
				return {}
			},
			avatarFn(item) {
				if (item.memberUuid == this.userInfo.uuid) {
					uni.navigateTo({
						url: '/pages/personCard/index'
					})
					return
				}
				uni.navigateTo({
					url: '/pages/personCard/index?uuid=' + item.memberUuid
				})
			},
			itemFn(item) {
				if (item.relUuid == this.personUuid) return
				this.personUuid = item.relUuid
				this.uuid = item.uuid
				this.type = item.type
				this.pageNum = 0
				item.unReadNum = 0
				this.init()
				this.initWS()
			},
			dubble(v) {
				if (v < 10) {
					return '0' + v
				}
				return v
			},
			async init() {
				await this.getChatRoomId()
				this.queryChatHistoryRecord()
				this.clearUnReadMsg()
			},
			getChatRoomId() { // 获取房间号
				return protal.getChatRoomId(this.personUuid).then(res => {
					this.roomId = res.data

					this.getSendStatus()
				})
			},
			getSendStatus() {
				protal.getSendStatus(this.roomId, this.personUuid).then(res => {
					this.statusDetail = res.data
				})
			},
			companyqueryDetail() { // 获取企业详情
				protal.companyqueryDetail(this.personUuid).then(res => {
					this.detail = res.data
				})
			},
			otherDetail() {
				protal.otherDetail(this.personUuid).then(res => {
					this.detail = res.data
				})
			},
			clearUnReadMsg() { // 清除未读消息
				return protal.clearUnReadMsg({
					friendUuid: this.personUuid
				})
			},
			queryChatHistoryRecord() { // 获取聊天历史记录
				this.pageNum++
				const params = {
					"friendUuid": this.personUuid,
					"pageNum": this.pageNum,
					"pageSize": 10
				}
				protal.queryChatHistoryRecord(params).then(res => {
					this.total = res.total
					if (this.pageNum == 1) {
						this.list = res.data
						this.scrollTop = this.oldTop
						this.$nextTick(() => {
							this.scrollTop = 100000
						})
						// #ifdef MP-ALIPAY
						this.lastTime = res.data[res.data.length - 1].createdTime
						this.loopGetChat() // 支付宝ws不支持订阅  直接轮询
						// #endif
					} else {
						this.list = [...res.data, ...this.list]
					}
				})
			},
			huimian() { // 发起线下会面
				this.showCardMask = true
			},
			sendMsg() { // 发送会话聊天
				if (!this.val.trim()) return
				const params = {
					"content": this.val,
					"contentType": 1,
					"friendUuid": this.personUuid,
					"roomId": this.roomId
				}
				protal.sendMsg(params).then(res => {
					if (res.code === '0000') {
						// #ifdef MP-ALIPAY
						this.loopGetChat(0)
						// #endif
						// #ifdef MP-WEIXIN
						this.list.push(res.data)
						this.val = ''
						this.scrollTop = this.oldTop
						this.$nextTick(() => {
							this.scrollTop = 100000
						})
						// #endif
						if (!this.statusDetail.unlimited) {
							this.getSendStatus()
						}
					}
				})
			},
			sendCallingCard() { // 发送名片
				this.showCardMask = true
			},
			cardConfirm() {
				this.showCardMask = false
				protal.sendCallingCard(0, this.personUuid).then(res => {
					if (res.code === '0000') {
						this.list.push(res.data)
						this.scrollTop = this.oldTop
						this.$nextTick(() => {
							this.scrollTop = 100000
						})
					}
				})
			},
			initWS() {
				// #ifdef MP-WEIXIN
				const that = this
				if (!this.stompWebsocket) {
					this.stompWebsocket = new WebSocketClient(wsUrl, "stompConnected")
					this.stompWebsocket.webSocketInit()
				}

				uni.$on('stompConnected', function(data) {
					if (!that.connectList.includes(that.personUuid)) {
						that.connectList.push(that.personUuid)

						data.subscribe(`/user/${ that.userInfo.uuid }/friend/${ that.personUuid }/msg`, function(
							res) {
							that.pageNum = 0
							that.queryChatHistoryRecord()
						})
					}
				})
				// #endif
			},
			loopGetChat(time) {
				if (time === 0) {
					if (this.loading) return
					clearInterval(this.timer)
					const params = {
						"friendUuid": this.personUuid,
						"pageNum": 1,
						"pageSize": 30,
						"firstMsgTime": this.lastTime
					}
					this.loading = true
					protal.queryChatHistoryRecord(params).then(res => {
						if (res.data && res.data.length) {
							this.lastTime = res.data[res.data.length - 1].createdTime
							this.list = [...this.list, ...res.data]
							this.val = ''
							this.scrollTop = this.oldTop
							this.$nextTick(() => {
								this.scrollTop = 100000
							})
						}
						this.loopGetChat()
						this.loading = false
					}).catch(err => {
						this.loading = false
					})
					return
				}
				this.timer = setInterval(() => {
					if (!this.lastTime) return
					const params = {
						"friendUuid": this.personUuid,
						"pageNum": 1,
						"pageSize": 30,
						"firstMsgTime": this.lastTime
					}
					this.loading = true
					protal.queryChatHistoryRecord(params).then(res => {
						if (res.data && res.data.length) {
							this.lastTime = res.data[res.data.length - 1].createdTime
							this.list = [...this.list, ...res.data]
							this.val = ''
							this.scrollTop = this.oldTop
							this.$nextTick(() => {
								this.scrollTop = 100000
							})
						}
						this.loading = false
					}).catch(err => {
						this.loading = false
					})
				}, 1000)
			},
			queryChatWindow() { // 聊天列表\
				const params = {
					leftPageNum: 1,
					pageSize: 9999
				}

				return protal.queryChatWindow(params).then(res => {
					this.waterfallList = res.data
				})
			},
			upper() {
				if (this.list.length < this.total) {
					this.queryChatHistoryRecord()
				}
			},
			lower() {},
			scroll(e) {
				this.oldTop = e.detail.scrollTop
			},
			closeFn() {
				this.$store.commit('setshowMask', '')
			},
			keyboardheightchange(event) {
				if (this.isPc) return
				this.inputTop = '-' + event.detail.height + 'px'
			},
			successFn(data) {
				// #ifdef MP-ALIPAY
				this.loopGetChat(0)
				// #endif
				// #ifdef MP-WEIXIN
				this.list.push(data)
				this.val = ''
				this.scrollTop = this.oldTop
				this.$nextTick(() => {
					this.scrollTop = 100000
				})
				// #endif
				this.showCardMask = false
			}
		}
	}
</script>

<style lang="scss" scoped>
	.chat {

		.bar-title {
			display: flex;
			align-items: center;
			width: 100%;

			.back-icon {
				width: 32rpx;
				height: 32rpx;
				padding: 14rpx;
				box-sizing: content-box;
			}

			.logo {
				width: 60rpx;
				height: 60rpx;
				border-radius: 50%;
				margin-right: 16rpx;
			}

			.title {
				flex: 1;
				padding-right: 136rpx;
				font-size: 34rpx;
				font-family: AlibabaPuHuiTi_3_65_Medium;
				display: flex;
				justify-content: center;
			}
		}

		.chat1 {
			padding-bottom: 160rpx;
			background-color: #F0F1FB;
			overflow: hidden;

			.scroll-Y {
				height: 100%;
				overflow: hidden;
			}

			.scroll-view-item {
				padding: 28rpx;

				.item {
					margin-bottom: 32rpx;

					.time {
						font-family: AlibabaPuHuiTi_3_55_Regular;
						font-size: 24rpx;
						color: #8A8E99;
						line-height: 24rpx;
						text-align: center;
						font-style: normal;
						margin: 20rpx 0 32rpx;
					}

					.item1 {
						display: flex;

						.avatar {
							width: 80rpx;
							height: 80rpx;
							border-radius: 50%;
							background-size: cover;
							background-position: center center;
							background-repeat: no-repeat;
						}

						.content {
							position: relative;

							.texts {
								max-width: 494rpx;
								padding: 20rpx;
								font-family: AlibabaPuHuiTi_3_55_Regular;
								font-size: 32rpx;
								color: #0A0F1A;
								line-height: 48rpx;
								text-align: right;
								font-style: normal;
								background-color: #fff;
								border-radius: 20rpx;
							}

							.card {
								width: 494rpx;
								font-family: AlibabaPuHuiTi_3_55_Regular;
								font-size: 32rpx;
								color: #0A0F1A;
								line-height: 48rpx;
								text-align: right;
								font-style: normal;
								background-color: #fff;
								border-radius: 20rpx;

								.card-title {
									border-bottom: 1px solid rgba(138, 142, 153, 0.30);
									height: 40px;
									display: flex;
									align-items: center;
									justify-content: space-between;
									padding: 0 20px;

									.left {
										padding: 0 7px;
										height: 20px;
										background: rgba(115, 80, 245, 0.1);
										border-radius: 10px;
										font-family: AlibabaPuHuiTi_3_55_Regular;
										font-size: 12px;
										color: #7350F5;
										line-height: 14px;
										text-align: left;
										font-style: normal;
										display: flex;
										align-items: center;
									}

									.right {
										font-family: AlibabaPuHuiTi_3_55_Regular;
										font-size: 12px;
										color: #22CC00;
										line-height: 14px;
										text-align: left;
										font-style: normal;
									}
								}

								.card-content {
									padding: 12px;

									.card-content1 {
										font-family: AlibabaPuHuiTi_3_65_Medium;
										font-size: 16px;
										color: #0A0F1A;
										line-height: 16px;
										text-align: left;
										font-style: normal;
										margin-bottom: 14px;
									}

									.card-content2 {
										margin-top: 4px;
										position: relative;

										.icon {
											position: absolute;
											left: 0;
											top: 0;
											width: 12px;
											height: 12px;
											transform: translateY(1px);
											overflow: hidden;
										}

										.text {
											padding-left: 16px;
											overflow: hidden;
											font-family: AlibabaPuHuiTi_3_45_Light;
											font-size: 12px;
											color: #000000;
											line-height: 14px;
											text-align: left;
											font-style: normal;
										}
									}

									.card-content3 {
										font-family: AlibabaPuHuiTi_3_45_Light;
										font-size: 11px;
										color: #7350F5;
										line-height: 14px;
										text-align: left;
										font-style: normal;
									}

									.card-content4 {
										display: flex;

										.btn {
											height: 28px;
											background: rgba(30, 35, 75, 0.1);
											border-radius: 14px;
											font-family: AlibabaPuHuiTi_3_65_Medium;
											font-size: 12px;
											color: rgba(30, 35, 75, 1);
											line-height: 17px;
											text-align: left;
											font-style: normal;
											display: flex;
											align-items: center;
											justify-content: center;
											margin-right: 8px;
											margin-top: 16px;
											padding: 0 18px;

											&.on {
												background-color: rgba(115, 80, 245, 1);
												color: #FFFFFF;
											}
										}
									}
								}
							}
						}

						.tips {
							width: 510rpx;
							margin: 0 auto;
							display: flex;
							justify-content: center;

							.tips-item1 {
								font-family: AlibabaPuHuiTi_3_55_Regular;
								font-size: 12px;
								color: #8A8E99;
								line-height: 16px;
								text-align: left;
								font-style: normal;
							}

							.tips-item2 {
								font-family: AlibabaPuHuiTi_3_55_Regular;
								font-size: 12px;
								color: #8A8E99;
								line-height: 16px;
								text-align: center;
								font-style: normal;
							}

							.tips-item3 {
								padding: 4px 10px;
								background: rgba(0, 0, 0, 0.2);
								border-radius: 8px;
								font-family: AlibabaPuHuiTi_3_55_Regular;
								font-size: 13px;
								color: #FFFFFF;
								line-height: 18px;
								font-style: normal;
							}
						}

						&.item-left {
							justify-content: flex-start;

							.content {
								text-align: left;
								margin-left: 20rpx;

								&:before {
									content: "";
									position: absolute;
									left: -11rpx;
									top: 32rpx;
									border-right: 12rpx solid #fff;
									border-top: 12rpx solid transparent;
									border-bottom: 12rpx solid transparent;
								}
							}
						}

						&.item-right {
							justify-content: flex-end;

							.avatar {
								order: 2;
							}

							.texts {
								background-color: #3C2DAA;
								color: #fff;
							}

							.content {
								margin-right: 20rpx;
								text-align: right;

								&:before {
									content: "";
									position: absolute;
									right: -11rpx;
									top: 32rpx;
									border-left: 12rpx solid #fff;
									border-top: 12rpx solid transparent;
									border-bottom: 12rpx solid transparent;
								}

								&.text-content::before {
									border-left-color: #3C2DAA;
								}
							}
						}
					}
				}
			}
		}

		.chat2 {
			position: fixed;
			left: 0;
			bottom: 0;
			width: 750rpx;
			padding-left: 28rpx;
			padding-right: 28rpx;
			padding-top: 10rpx;
			// padding-bottom: constant(safe-area-inset-bottom);
			// padding-bottom: env(safe-area-inset-bottom);
			box-sizing: border-box;
			background-color: #fff;
			height: 130rpx;
			display: flex;

			.chat2-1 {

				.icon {
					display: block;
					width: 40rpx;
					height: 40rpx;
					margin: 0 auto 8rpx;
				}

				.span {
					font-family: AlibabaPuHuiTi_3_65_Medium;
					font-size: 24rpx;
					color: #0A0F1A;
					line-height: 24rpx;
					text-align: center;
					font-style: normal;
				}
			}
			
			.send-icon {
				position: absolute;
				top: 0;
				right: 0;
				width: 110rpx;
				height: 76rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				
				.icon {
					width: 34rpx;
				}
			}

			.chat2-3 {
				height: 50rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				font-family: AlibabaPuHuiTi_3_65_Medium;
				font-size: 32rpx;
				color: #FFFFFF;
				line-height: 48rpx;
				text-align: left;
				font-style: normal;
				margin-left: 36rpx;
				transform: translateY(14rpx);
			}

			.chat2-4 {
				width: 160rpx;
				height: 76rpx;
				border-radius: 38rpx;
				background: #3C2DAA;
				display: flex;
				align-items: center;
				justify-content: center;
				font-family: AlibabaPuHuiTi_3_65_Medium;
				font-size: 32rpx;
				color: #FFFFFF;
				line-height: 48rpx;
				text-align: left;
				font-style: normal;
				margin-left: 12rpx;
			}
		}
	}
</style>